/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp.adapters;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import android.content.Context;
import android.content.res.Resources;
import dk.redia.lib.log.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import dk.redia.lib.utils.DateUtils;
import dk.redia.libraryapp.R;
import dk.redia.libraryapp.model.Loan;
import dk.redia.libraryapp.net.LoansRemoteListManager;
import dk.redia.libraryapp.net.RemoteListManager;

public class LoansAdapter extends RemoteListAdapter {

	private static final String logTag = "LoansAdapter";
	private Context context;
	private Set<Integer> selectedIndices;
//	private Vector<Loan> loans;
//	private int loanCount;
//	private int lastLoadedIndex;

//	private Map<Integer, View> loanViews; // Map view to indices into loans list
	private Set<Integer> loansRenewing;
	
	public LoansAdapter(Context context) {
		super(new LoansRemoteListManager());
//		this.loans = new Vector<Loan>();
	    selectedIndices = new HashSet<Integer>();
		this.context = context;
//		this.loanCount = 0;
//		this.loanViews = new HashMap<Integer, View>();
//		this.lastLoadedIndex = 0;
		loansRenewing = new HashSet<Integer>();
//		listManager = new LoansRemoteListManager();
//		listManager.addListener(this);
	}
	
	public int getSelectedCount() {
		return selectedIndices.size();
	}
	
	public Set<Integer> getSelectedIndices() {
		return selectedIndices;
	}
	
	public int getRenewableCount() {
		return (Integer)getExtraResultData(LoansRemoteListManager.EXTRA_RESULT_DATA_RESERVABLE_COUNT);
	}
	
	public View getViewByState(View v, int state) {
		Log.d(logTag, "Setting state " + state + " on view");
		TextView creatorTextView = (TextView)v.findViewById(R.id.myLoansItemCreatorTextView);
		TextView deadlineTextView = (TextView)v.findViewById(R.id.myLoansItemDeadlineTextView);
		TextView titleTextView = (TextView)v.findViewById(R.id.myLoansItemTitleTextView);
//		Button renewButton = (Button)v.findViewById(R.id.myLoansRenewButton);
		ProgressBar loadingProgressBar = (ProgressBar)v.findViewById(R.id.myLoansItemLoadingProgressBar);
		TextView staticDeadlineTextView = (TextView)v.findViewById(R.id.myLoansItemDeadlineStaticTextView);
		CheckBox selectedCheckbox = (CheckBox)v.findViewById(R.id.myLoansItemSelectedCheckBox);
		
		if (state==RemoteListManager.STATE_LOADED) {
			creatorTextView.setVisibility(View.VISIBLE);
			deadlineTextView.setVisibility(View.VISIBLE);
			titleTextView.setVisibility(View.VISIBLE);
//			renewButton.setVisibility(View.VISIBLE);
//			renewProgressBar.setVisibility(View.VISIBLE);
			staticDeadlineTextView.setVisibility(View.VISIBLE);
			loadingProgressBar.setVisibility(View.GONE);
			selectedCheckbox.setVisibility(View.VISIBLE);
		} else {
			creatorTextView.setVisibility(View.GONE);
			deadlineTextView.setVisibility(View.GONE);
			titleTextView.setVisibility(View.GONE);
			selectedCheckbox.setVisibility(View.GONE);
//			renewButton.setVisibility(View.GONE);
//			renewProgressBar.setVisibility(View.GONE);
			staticDeadlineTextView.setVisibility(View.GONE);
			loadingProgressBar.setVisibility(View.VISIBLE);
		}
		return v;
		
	}
	
	public View getView(final int position, final View convertView, final ViewGroup parent) {

		// Construct a new view, if one wasn't provided
		View v;
		if (convertView==null) {
			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.myloansitem, null);
		} else {
			v = convertView;
		}
		ensureIndexLoad(position);
		int loadState = getLoadState(position);
		
		// Keep track of which loan maps to which view
		Log.d(LoansAdapter.logTag, "Storing view for position " + position);
		updateViewCache(position, null, v);
		
		v = getViewByState(v, loadState);
		v.setClickable(true);
		
		if (loadState==RemoteListManager.STATE_LOADED) {
			Loan loan = (Loan)getItem(position);
			if (loan!=null) {
				
				updateViewCache(position, loan.getLoanId(), v);
				TextView creatorTextView = (TextView)v.findViewById(R.id.myLoansItemCreatorTextView);
				TextView deadlineTextView = (TextView)v.findViewById(R.id.myLoansItemDeadlineTextView);
				TextView titleTextView = (TextView)v.findViewById(R.id.myLoansItemTitleTextView);
//				Button renewButton = (Button)v.findViewById(R.id.myLoansRenewButton);
//				ProgressBar renewProgressBar = (ProgressBar)v.findViewById(R.id.myLoansItemRenewProgressBar);
				ProgressBar loadingProgressBar = (ProgressBar)v.findViewById(R.id.myLoansItemLoadingProgressBar);
				CheckBox selectedeCheckBox = (CheckBox)v.findViewById(R.id.myLoansItemSelectedCheckBox);
				
				loadingProgressBar.setVisibility(View.GONE);
				
				Log.d(LoansAdapter.logTag, "Loan data is loaded. Updating data");
//				renewButton.setTag(loan);
				
				Resources r = context.getResources();
				
				String creatorTextTmpl = r.getString(R.string.myLoansCreatorText);
				String titleTextTmpl = r.getString(R.string.myLoansTitleText);
				String deadlineTextTmpl = r.getString(R.string.myLoansDeadlineText);
				
				String author = String.format(creatorTextTmpl, loan.getAuthor());
				String title = String.format(titleTextTmpl, loan.getTitle());
				String deadline = String.format(deadlineTextTmpl, DateUtils.formatDate(loan.getLoanDueDate()));
				
				if (author==null || author.length()==0 || author.equals("undefined") || author.equals("null")) {
					creatorTextView.setVisibility(View.INVISIBLE); 
				} else {
					creatorTextView.setText(author);
				}
				deadlineTextView.setText(deadline);
				
				Date today = new Date();
				if (today.after(loan.getLoanDueDate())) {
					int color = v.getResources().getColor(R.color.myLoansDeadlinePastBackgroundColor);
					deadlineTextView.setBackgroundColor(color);
				}
				titleTextView.setText(title);
//				renewButton.setEnabled(loan.isLoanIsRenewable());
		
				Log.d(LoansAdapter.logTag, "Loan is renewing: " + loansRenewing.contains(position));
				
				if (loansRenewing.contains(position)) {
					Log.d(logTag, "Loan at index " + position +  " is being renewed, showing throbber");
//					renewProgressBar.setVisibility(View.VISIBLE);
//					renewButton.setVisibility(View.GONE);
				} else {
					Log.d(logTag, "Loan at index " + position + " is not being renewed.");
//					renewProgressBar.setVisibility(View.GONE);
//					renewButton.setVisibility(View.VISIBLE);
				}
				
				v.setTag(position);
				selectedeCheckBox.setVisibility(loan.getLoanIsRenewable() ? View.VISIBLE : View.INVISIBLE);
				selectedeCheckBox.setChecked(selectedIndices.contains(position));
				selectedeCheckBox.setTag(position);
				
			} else {
				Log.d(LoansAdapter.logTag, "Unable to retrieve loan with position " + position + ", we are probably loading it right now in the background");
			}
		} else if (loadState==RemoteListManager.STATE_NOT_LOADED) {
			// Nothing to do, view doesn't need any data
		} else if (loadState==RemoteListManager.STATE_LOADING) {
			// Nothing to do, view doesn't need any data
		} else {
			Log.e(LoansAdapter.logTag, "Unknown load state: " + loadState);
		}

		return v;
	}

	public void setIsRenewing(int index, boolean renewing) {
		// Only repaint if stuff really changed
//		boolean wasRenewing = loansRenewing.contains(arg0);
//		if (wasRenewing==renewing) {
//			return;
//		}
		if (renewing) {
			loansRenewing.add(index);
		} else {
			loansRenewing.remove(index);
		}
		View v = getItemView(index);
		if (v!=null) {
			Log.d(logTag, "Invalidating view at index " + index);
			getView(index, v, null).invalidate();
		} else {
			Log.d(logTag, "Currently no view associated with index " + index);
		}
	}

	public void setSelected(int index, boolean b) {
		if (b) {
			selectedIndices.add(index);
		} else {
			selectedIndices.remove(index);
		}
	}
}
